package com.ztao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.wemedia.dtos.WmLoginDto;
import com.heima.model.common.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.ztao.mapper.WmUserMapper;
import com.ztao.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    @Resource
    private WmUserMapper wmUserMapper;
    @Override
    public ResponseResult login(WmLoginDto dto) {
       if(StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
           return ResponseResult.errorResult(500,"用户名或密码不能为空");
       }
        QueryWrapper<WmUser> queryWrapper=new QueryWrapper<>();
       queryWrapper.lambda().eq(WmUser::getName,dto.getName());
        WmUser wmUser = this.wmUserMapper.selectOne(queryWrapper);
        if(wmUser==null){
             return ResponseResult.errorResult(500,"账号不存在");
        }
        String pwd= wmUser.getSalt();;
        String pwd1=dto.getPassword();
        pwd1= DigestUtils.md5DigestAsHex((pwd1+pwd).getBytes());
        if(!pwd1.equals(wmUser.getPassword())){
            return ResponseResult.errorResult(500,"密码错误");
        }
        Map<String,Object> map=new HashMap<>();
        map.put("token", AppJwtUtil.getToken(wmUser.getId().longValue()));
        wmUser.setPassword(null);
        wmUser.setSalt(null);
        map.put("user",wmUser);
        return ResponseResult.okResult(map);

    }
}
